package com.imooc.coupon.filter;

import com.google.common.util.concurrent.RateLimiter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * 限流过滤器 用于服务的限流
 */
@Slf4j
@Component
public class RateLimterFilter extends AbstractPreZuulFilter {
    /*限流器 每秒可以获取两个令牌*/
    RateLimiter rateLimiter = RateLimiter.create(2.0);

    @Override
    public int filterOrder() {
        return 2;
    }

    @Override
    protected Object cRun() {
        HttpServletRequest request = context.getRequest();
        //尝试去获取令牌
        if(rateLimiter.tryAcquire()){
            log.info("get rate token success");
        }else{
            log.error("rate limit error", request.getRequestURI());
            return fali(403, "get rate token fail " );
        }
        return null;
    }
}
